//
//  HSImageDownloader.m
//  AFNetworking
//
//  Created by huang on 2018/8/21.
//

#import "HSImageDownloader.h"
#import "UIImageView+WebCache.h"
#import "UIButton+WebCache.h"

@implementation HSImageDownloader

+ (UIImage *)placeholderImage
{
    return [UIImage imageWithColor:[UIColor lightGrayColor] cornerRadius:0];
}

#pragma mark 下载图片(UIImageView)
+ (void)downloadImage:(NSString *)urlStr place:(UIImage *)place imageView:(UIImageView *)imageView
{
    [self downloadImage:urlStr place:place imageView:imageView success:nil failure:nil];
}

#pragma mark 下载图片(UIButton)
+ (void)downloadImageWithURL:(NSURL *)url button:(UIButton *)button forState:(UIControlState)state
{
    [button sd_setImageWithURL:url forState:state];
}

#pragma mark 下载图片(UIImageView)
+ (void)downloadImage:(NSString *)urlStr place:(UIImage *)place imageView:(UIImageView *)imageView success:(DownLoadSuccessBlock)success failure:(DownLoadFailureBlock)failure
{
    urlStr = [urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURL *url = [NSURL URLWithString:urlStr];
    
    if (place == nil) {
        place = [self placeholderImage];
    }
    
    [imageView sd_setImageWithURL:url placeholderImage:place options:0 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        if (error == nil) {
            if (success == nil) return ;
            success(image);
        }else {
            if (failure == nil) return;
            failure();
        }
    }];
}

@end

@implementation UIImage (DD)

static CGFloat edgeSizeFromCornerRadius(CGFloat cornerRadius)
{
    return cornerRadius * 2 + 1;
}

#pragma mark 根据颜色值生成图片
+ (UIImage *)imageWithColor:(UIColor *)color cornerRadius:(CGFloat)cornerRadius
{
    CGFloat minEdgeSize = edgeSizeFromCornerRadius(cornerRadius);
    CGRect rect = CGRectMake(0, 0, minEdgeSize, minEdgeSize);
    UIBezierPath *roundedRect = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:cornerRadius];
    roundedRect.lineWidth = 0;
    UIGraphicsBeginImageContextWithOptions(rect.size, NO, 0.0f);
    [color setFill];
    [roundedRect fill];
    [roundedRect stroke];
    [roundedRect addClip];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return [image resizableImageWithCapInsets:UIEdgeInsetsMake(cornerRadius, cornerRadius, cornerRadius, cornerRadius)];
}

@end
